package com.payment.system.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.payment.system.domain.*;
import com.payment.system.mapper.*;
import com.payment.system.vo.AnnouncementVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.payment.common.base.AjaxResult;
import com.payment.common.constant.Constants;
import com.payment.common.support.Convert;
import com.payment.common.type.CreateStatusType;
import com.payment.common.utils.DateUtils;
import com.payment.common.utils.StringUtils;
import com.payment.system.service.IAnnouncementService;


/**
 * 公告 服务层实现
 *
 * @author payment
 * @date 2019-01-14
 */
@Service
public class AnnouncementServiceImpl implements IAnnouncementService {
    @Autowired
    private AnnouncementMapper announcementMapper;
    @Autowired
    private MoneyChangeMapper moneyChangeMapper;

    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private MerchantIncreaseLimitMapper merchantIncreaseLimitMapper;
    @Autowired
    private PlanNewMapper planNewMapper;

    @Autowired
    private PaymentOrderMapper orderMapper;

    /**
     * 查询公告信息
     *
     * @param id 公告ID
     * @return 公告信息
     */
    @Override
    public Announcement selectAnnouncementById(String id) {
        return announcementMapper.selectAnnouncementById(id);
    }

    /**
     * 查询公告列表
     *
     * @param announcement 公告信息
     * @return 公告集合
     */
    @Override
    public List<Announcement> selectAnnouncementList(Announcement announcement) {
        return announcementMapper.selectAnnouncementList(announcement);
    }

    /**
     * 新增公告
     *
     * @param announcement 公告信息
     * @return 结果
     */
    @Override
    public int insertAnnouncement(Announcement announcement) {
        String uuid = StringUtils.randomUUID();
        announcement.setId(uuid);
        if (StringUtils.equals(announcement.getStatus(), CreateStatusType.CREATE.getCode())) {
            Map<String, String> parm = new HashMap<String, String>(16);
            parm.put("id", "");
            parm.put("msg", announcement.getContent());
            parm.put("dateTime", DateUtils.getTime());
            parm.put("title", announcement.getTitle());
            //JPushUtil.jpushAll(parm);
        }
        //保存普通公告
        return announcementMapper.insertAnnouncement(announcement);

    }

    /**
     * 修改公告
     *
     * @param announcement 公告信息
     * @return 结果
     */
    @Override
    public int updateAnnouncement(Announcement announcement) {

        if (StringUtils.equals(announcement.getStatus(), CreateStatusType.CREATE.getCode())) {
            Map<String, String> parm = new HashMap<String, String>(16);
            parm.put("id", "");
            parm.put("msg", announcement.getContent());
            parm.put("dateTime", DateUtils.getTime());
            parm.put("title", announcement.getTitle());
            // JPushUtil.jpushAll(parm);
        }

        return announcementMapper.updateAnnouncement(announcement);
    }

    /**
     * 删除公告对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteAnnouncementByIds(String ids) {
        return announcementMapper.deleteAnnouncementByIds(Convert.toStrArray(ids));
    }

    @Override
    public AjaxResult updateStatusById(String id, String status) {
        if (StringUtils.isEmpty(id) || StringUtils.isEmpty(status)) {
            return AjaxResult.error("获取信息失败：缺失参数！");
        }
        int r = announcementMapper.changeStatusById(id, status);
        return r > 0 ? AjaxResult.success() : AjaxResult.error("修改状态失败，请联系后台管理人员！");
    }

    //app端 公告列表aaa
    @Override
    public AjaxResult selectAnnouncementListByApp(String merchantId, Integer type) {
        List<AnnouncementVo> announcementList = announcementMapper.selectAnnouncementListByApp();
        //查询最新20条升级分润记录
        List<Map<String, Object>> list = moneyChangeMapper.selectPaymentOrderListByUpgrade();
        if (list != null && list.size() > 0) {
            for (Map<String, Object> map : list) {
                String merName = map.get("merName").toString();
                merName = merName.replaceAll(merName.substring(1, merName.length()), "**");
                String userName = map.get("userName").toString();
                userName = userName.replaceAll(userName.substring(1, userName.length()), "**");

                Integer orderType = Integer.parseInt(map.get("orderType").toString());
                String type1 = "";
                StringBuilder content = new StringBuilder();
                if (orderType.equals(6)) {
                    type1 = "VIP升级";
                } else if (orderType.equals(61)) {
                    type1 = "合伙人升级";
                }
                String profitType = "";
                String moneyType = map.get("moneyType").toString();
                if ("10D".equals(moneyType)) {
                    profitType = "合伙人分润";
                } else if ("10E".equals(moneyType)) {
                    profitType = "管理奖";
                } else if ("10C".equals(moneyType)) {
                    profitType = "升级分佣";
                } else {
                    profitType = "分佣";
                }
                BigDecimal trxAmt = (BigDecimal) map.get("trxAmt");
                content.append(userName).append("：").append(type1).append("，").append(merName).append("：").append(profitType).append(trxAmt.setScale(2, BigDecimal.ROUND_UP));
                AnnouncementVo announcement = new AnnouncementVo();
                announcement.setTitle(content.toString());
                announcement.setUpdateDate(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, map.get("createTime").toString()));
                announcement.setContent(content.toString());
                announcementList.add(announcement);

            }
        }

        return AjaxResult.successAndData("获取公告列表成功！", announcementList);
    }

    @Override
    public List<Map<String, Object>> selectAnnouncementAgent(String announcementId) {
        List<Map<String, Object>> trees = new ArrayList<Map<String, Object>>();
        Map<String, Object> deptMap1 = new HashMap<String, Object>(16);
        deptMap1.put("全部", "全部");
        deptMap1.put("name", "全部");
        trees.add(deptMap1);
        return trees;
    }

    // app 分润推送
    @Override
    public AjaxResult profitList(String merchantId, Integer pageNum, Integer pageSize) {
        if (StringUtils.isEmpty(merchantId) || pageNum == null || pageSize == null) {
            return AjaxResult.error(1, "获取分润信息失败：缺失参数");
        }
        Merchant merchant = merchantMapper.selectMerchantById(merchantId);
        if (merchant == null) {
            return AjaxResult.error(2, "获取分润信息失败：该商户不存在");
        }

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map1 = new HashMap<String, Object>(16);
        // 分润推送
        List<MoneyChange> moneyChangeList = moneyChangeMapper.selectprofitList(merchantId, merchant.getMerchantNo(),
                pageNum * pageSize, pageSize);
        if (moneyChangeList != null && moneyChangeList.size() > 0) {
            for (MoneyChange moneyChange : moneyChangeList) {
                Map<String, Object> map = new HashMap<String, Object>(16);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formatStr = formatter.format(moneyChange.getCreateTime());
                map.put("id", moneyChange.getId());
                map.put("content", Constants.PROFIT_REMIND_ONE + formatStr + Constants.PROFIT_REMIND_TWO
                        + moneyChange.getTrxAmt() + Constants.PROFIT_REMIND_THREE);
                map.put("type", 2);
                map.put("dateTime", DateUtils.getTime());
                list.add(map);
            }

        } else {
            map1.put("id", "");
            map1.put("content", "您暂无分润信息");
            map1.put("type", 1);
            map1.put("dateTime", DateUtils.getTime());
            list.add(map1);
        }
        return AjaxResult.successAndData("获取分润信息成功", list);
    }


    /**
     * app 还款提醒
     *
     * @param merchantId
     * @param type
     * @return
     */
    @Override
    public AjaxResult billRemind(String merchantId, Integer type) {
        if (StringUtils.isEmpty(merchantId) || type == null) {
            return AjaxResult.error(1, "获取还款提醒失败：缺失参数");
        }
        Merchant merchant = merchantMapper.selectMerchantById(merchantId);
        if (merchant == null) {
            return AjaxResult.error(2, "获取还款提醒失败：该商户不存在");
        }
        //获取用户信用卡列表
        List<MerchantIncreaseLimit> limitList = merchantIncreaseLimitMapper.selectMerchantIncreaseLimitByMerchantId(merchantId);
        // 还款提醒:判断还款日，是否制定计划，激光推送，发送提示信息
        Map<String, Object> map = new HashMap<String, Object>(16);
        List<Map<String, Object>> list = new ArrayList<>();
        if (limitList != null && limitList.size() > 0) {
            for (MerchantIncreaseLimit limit : limitList) {
                if (limit.getBillDay() != null && limit.getRepaymentDay() != null && !limit.getBillDay().equals("")
                        && !limit.getRepaymentDay().equals("")) {
                    // 账单日
                    int billDay = Integer.parseInt(limit.getBillDay());
                    Calendar time = Calendar.getInstance();
                    Calendar time2 = Calendar.getInstance();
                    // 还款日
                    int repaymentDay = Integer.parseInt(limit.getRepaymentDay());
                    //还款日当月
                    if ((repaymentDay + 30 - billDay) > 18) {
                        //设置还款日
                        time.set(Calendar.DATE, repaymentDay + 30);
                        //设置账单日
                        time2.set(Calendar.DATE, billDay);
                    } else {//还款日下个月
                        //设置还款日的月份
                        time2.set(Calendar.MONTH, time2.get(Calendar.MONTH) - 1);
                        //设置还款日
                        time.set(Calendar.DATE, repaymentDay);
                        //设置账单日
                        time2.set(Calendar.DATE, billDay);
                    }
                    Date newDate = new Date();
                    if (newDate.getTime() <= time.getTime().getTime() && newDate.getTime() >= time2.getTime().getTime()) {
                        // 计划判断 状态(0待执行1执行中2失败3成功4暂停5删除)
                        int r = planNewMapper.selectPlanByCardNumberAndMerchantId(merchantId, limit.getID());
                        if (r > 0) {
                            Map<String, Object> map1 = new HashMap<String, Object>(16);
                            String bankAccount = limit.getBankAccount();
                            bankAccount = bankAccount.substring(bankAccount.length() - 4, bankAccount.length());
                            // 返回提示信息
                            String msg = Constants.BILL_REMIND_ONE + bankAccount + Constants.BILL_REMIND_TWO
                                    + limit.getBillDay() + Constants.BILL_REMIND_THREE;
                            map1.put("id", limit.getID());
                            map1.put("content", msg);
                            map1.put("type", 1);
                            map1.put("dateTime", DateUtils.getTime());
                            list.add(map1);
                        }
                    }
                }
            }
        } else {
            map.put("id", "");
            map.put("content", "您暂无绑定信用卡");
            map.put("type", 0);
            list.add(map);
        }

        return AjaxResult.successAndData("获取还款提醒成功", list);
    }

}
